package middleware

import (
	"daily-blog/pkg"
	"github.com/gin-gonic/gin"
	"strings"
)

//AuthMiddleware
func AuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			pkg.FailWithMessage("认证码为空", c)
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			pkg.FailWithMessage("token不存在", c)
			c.Abort()
			return
		}

		mc, err := pkg.ParseToken(parts[1])
		if err != nil {
			pkg.FailWithMessage("认证失败", c)
			c.Abort()
			return
		}
		c.Set("userId", mc.UUID)
		c.Next()
	}
}
